#pragma once

#include "base/base.h"

namespace l8
{

// ----------------------------------------------------------------------------
// BitField is a help template for encoding and decode bitfield with
// unsigned content.
template<class T, int shift, int size>
class BitField
{
public:
    // Tells whether the provided value fits into the bit field.
    static bool is_valid(T value)
    {
        return (static_cast<uint32_t>(value) & ~((1U << (size)) - 1)) == 0;
    }

    // Returns a uint32_t mask of bit field.
    static uint32_t mask()
    {
        return (1U << (size + shift)) - (1U << shift);
    }

    // Returns a uint32_t with the bit field value encoded.
    static uint32_t encode(T value)
    {
        ASSERT(is_valid(value));
        return static_cast<uint32_t>(value) << shift;
    }

    // Extracts the bit field from the value.
    static T decode(uint32_t value)
    {
        return static_cast<T>((value >> shift) & ((1U << (size)) - 1));
    }
};

}

